# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os
from flask_cors import CORS
app = Flask(__name__)

# 这是您的上传文件夹路径
UPLOAD_FOLDER = '/home/cs/map'  # 请根据您的实际情况修改这个路径
ALLOWED_EXTENSIONS = {'pgm'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app, resources={r"/upload": {"origins": "*"}})
# 通过文件扩展名验证上传的文件
def is_image_file(file):
    allowed_mimetypes = ['image/png', 'image/jpeg', 'image/gif', 'image/pgm']  # 根据需要添加更多
    return file.mimetype in allowed_mimetypes

@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查是否有文件在请求中
    print(request.files)

    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    # 如果用户未选择文件，浏览器可能提交一个没有文件的部分
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if file and is_image_file(file):  # 在这里添加您想允许的文件类型
        # 为了安全性考虑，不使用客户端提供的文件名路径部分
        filename = secure_filename(file.filename)
        
        # 如果文件夹不存在，则创建文件夹
        if not os.path.exists(app.config['UPLOAD_FOLDER']):
            os.makedirs(app.config['UPLOAD_FOLDER'])

        # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        print('Saving to:', save_path)
        file.save(save_path)
        return jsonify({'message': 'File uploaded successfully'}), 200
    else:
        return jsonify({'error': 'Uploaded file is not an image'}), 400  # 如果文件类型不是所允许的类型

if __name__ == '__main__':
    # 运行flask应用程序
    app.run(debug=True, host='0.0.0.0', port=5000)  # 如果需要的话，可以修改端口号
